package com.aisino.interceptor;

import com.aisino.annotation.RequireAuth;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Base64;

/**
 * @author guochuantao
 * @version 1.0
 * @description 需要基础验证的拦截器
 * @since 2024/7/22 上午10:53
 */
public class RequireAuthInterceptor implements HandlerInterceptor {
    final Base64.Decoder decoder = Base64.getDecoder();
    // final Base64.Encoder encoder = Base64.getEncoder();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 请求目标为 method of controller，需要进行验证
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Object object = handlerMethod.getMethodAnnotation(RequireAuth.class);

            /* 方法没有 @RequireAuth 注解， 放行 */
            if (object == null) {
                return true; // 放行
            }

            /* 方法有 @RequireAuth 注解，需要拦截校验 */
            // 没有 Authorization 请求头，或者 Authorization 认证信息不通过，拦截
            if (!isAuth(request, response)) {
                return false; // 拦截
            }

            // 验证通过，放行
            return true;
        }

        // 请求目标不是 method of controller, 放行
        return true;
    }

    private boolean isAuth(HttpServletRequest req, HttpServletResponse res) {
        String base6AuthStr = req.getHeader("Authorization");
        System.out.println("base6AuthStr=" + base6AuthStr); // base6AuthStr=Basic YWFhOmFhYQ==
        if (base6AuthStr == null) {
            res.setStatus(401);
            res.addHeader("WWW-Authenticate", "basic realm=\"no auth\"");
            return false;
        }

        String authStr = new String(decoder.decode(base6AuthStr.substring(6).getBytes()));
        System.out.println("authStr=" + authStr); // authStr=xxx:xxx

        String[] arr = authStr.split(":");
        if (arr != null && arr.length == 2) {
            String username = arr[0];
            String password = arr[1];
            // 校验用户名和密码
            if ("test".equals(username) && "123456".equals(password)) {
                return true;
            }
        }

        res.setStatus(401);
        res.addHeader("WWW-Authenticate", "basic realm=\"no auth\"");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
